package com.atguigu.gulimall.seckill.config;

import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import sun.text.resources.cldr.yav.FormatData_yav;

import java.util.concurrent.TimeUnit;

/**
 * 每天晚上3点，可以上架最近3天 需要秒杀的商品
 * 当天 00:00:00  23:59:59
 * 明天 00:00:00  23:59:59
 * 后天 00:00:00  23:59:59
 */
@Slf4j
@Service
public class ScheduledConfig {
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;
    private final String UPLOAD_LOCK = "seckill:upload:lock";

    @Scheduled(cron = "*/3 * * * * ?")
    public void uploadSeckillSkuLatest3Days() {
        // 添加分布式锁,只有获取锁的人，才能执行
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        // 10秒 超时
        lock.lock(10, TimeUnit.SECONDS);
        try {
            log.info("上架秒杀信息");
            // 1.重复上架，无需处理
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }
    }
}
